package com.ms.pda.components

import android.content.Context
import android.os.Bundle
import android.widget.TextView
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.StringUtils
import com.lxj.xpopup.core.CenterPopupView
import com.ms.pda.R
import com.ms.pda.model.Constants
import com.ms.pda.activity.LoginActivity
import com.ms.pda.activity.SubmitFailedActivity
import rxhttp.RxHttpPlugins
import rxhttp.wrapper.param.Param

class WarnDialog(context: Context, code: Int) : CenterPopupView(context) {

    private var mCode: Int? = 0
    private var mContentTv: TextView? = null
    private var mException: Throwable? = null
    private var mFrom: Int? = null

    init {
        mCode = code
    }

    constructor(context: Context, code: Int, exception: Throwable?, from: Int?) : this(
        context,
        code
    ) {
        mCode = code
        mException = exception
        mFrom = from
    }

    override fun getImplLayoutId(): Int {
        return R.layout.dialog_failed
    }

    override fun onCreate() {
        super.onCreate()
        mContentTv = findViewById(R.id.failed_content)
        val confirm = findViewById<TextView?>(R.id.failed_confirm)
        when (mCode) {
            424 -> {
                confirm?.setOnClickListener {
                    smartDismiss()
                    RxHttpPlugins.init(RxHttpPlugins.getOkHttpClient())
                        .setDebug(Constants.DEBUG)
                        .setOnParamAssembly { param: Param<*>? -> param }
                    SPUtils.getInstance().remove(Constants.LOGIN_INFO)
                    SPUtils.getInstance().remove(Constants.TENANT_DOMAIN)
                    ActivityUtils.finishAllActivities()
                    ActivityUtils.startActivity(LoginActivity::class.java)
                }
            }
            2 -> {
                confirm?.text = context.getString(R.string.check)
                confirm?.setOnClickListener {
                    smartDismiss()
                    val bundle = Bundle()
                    bundle.putString(Constants.EXTRA_KEY, mException?.message)
                    mFrom?.let {
                        bundle.putInt(Constants.FROM_KEY, it)
                    }
                    ActivityUtils.startActivity(bundle, SubmitFailedActivity::class.java)
                }
            }
            else -> {
                confirm?.setOnClickListener { smartDismiss() }
            }
        }
    }

    fun setContent(content: String?) {
        if (!StringUtils.isTrimEmpty(content)) mContentTv?.text = content
    }


}